package figure8.GUI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.util.HashMap;
import java.util.Map;

import javax.swing.BoxLayout;
import javax.swing.JPanel;

import figure8.Controller;
import figure8.Project;
import figure8.Track;
import figure8.events.TrackAddedEvent;
import figure8.events.TrackChangedEvent;
import figure8.events.TrackEventListener;
import figure8.events.TrackRemovedEvent;

/**
 * This class is a simple panel to contain all the panels for a project's track
 * in a vertical list.
 */
public class TrackList extends JPanel implements TrackEventListener {
	private static final long serialVersionUID = 9073410758863230864L;
	
	protected Controller controller;
	
	protected Project project;
	protected JPanel container;
	
	protected Map<Track, TrackPanel> panels;
	
	public TrackList(Controller controller, Project project) {
		this.controller = controller;
		
		this.project = project;
		this.panels = new HashMap<Track, TrackPanel>();
		
		project.addTrackEventListener(this);
		
		this.setLayout(new BorderLayout());
		this.setBackground(Color.white);
		
		/* The container is used to keep all of the TrackPanels in a vertical list
		 * which can be put into a single BorderLayout PAGE_START section so they
		 * resize only horizontally.
		 */
		this.container = new JPanel();
		this.container.setLayout(new BoxLayout(this.container, BoxLayout.Y_AXIS));
		
		for (Track track : project.getTracks()) {
			TrackPanel panel = track.makeTrackPanel(this.controller);
			
			this.panels.put(track, panel);
			this.container.add(panel);
		}
		
		this.add(this.container, BorderLayout.PAGE_START);
	}
	
	/** The TrackList is a listener on the Project, and so whenever a new track
      * is added to the Project, this function will be called.
      */
	@Override
	public void trackAdded(TrackAddedEvent event) {
		Track track = event.getTrack();
		TrackPanel panel = track.makeTrackPanel(this.controller);
		
		this.panels.put(track, panel);
		this.container.add(panel);
		
		this.controller.getWindow().getFrame().pack();
	}

	@Override
	public void trackRemoved(TrackRemovedEvent event) {
		Track track = event.getTrack();
		TrackPanel panel = this.panels.get(track);
		
		this.panels.remove(track);
		
		try {
			this.container.remove(panel);
		} catch (Exception e) {
			
		}
			
		this.controller.getWindow().getFrame().pack();
	}
	
	//Will use in order to alter the graphs of tracks
	/*public void applyChanges(int waveOn) {
		System.err.println("TrackList: " + waveOn);
		int num = 0;
		for(Track key : this.panels.keySet())
		{
			System.err.println("Inner For: " + key.isWAV());
			if(key.isWAV() == true)
			{
				System.err.println("Num: " + num);
				num++;
			}
		}
		
	}*/
}
